import {
	sendSharedUserId
} from "@/request/api.js";
export default {
	appVersion: 'v1.0',
	debounce(func, wait) {
		let timeout;
		return function() {
			const context = this;
			const args = [...arguments];
			if (timeout) clearTimeout(timeout);
			const callNow = !timeout;
			timeout = setTimeout(() => {
				timeout = null;
			}, wait)
			if (callNow) func.apply(context, args)
		}
	},

	// 节流
	throttle(fn, time) {
		var timer = null
		return function() {
			if (timer) return;
			timer = setTimeout(() => {
				fn();
				timer = null
			}, time * 1000)
		}
	},


	getPolicyBase64() {
		let date = new Date();
		date.setHours(date.getHours() + 87600);
		let srcT = date.toISOString();
		const policyText = {
			"expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
			"conditions": [
				["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
			]
		};
		const policyBase64 = base64.encode(JSON.stringify(policyText));
		return policyBase64;
	},




	// 设置标题
	setRepairTitle(index) {
		let repairType = this.repairType;
		for (var key in repairType) {
			if (repairType[key].index == index) {
				uni.setNavigationBarTitle({
					title: repairType[key].title
				});
			}
		}
	},

	// 设置广告显示时间
	setAdTime(load = false) {
		// 当前时间
		let timeStamp = Date.parse(new Date());
		// 设置过期期限
		let expiration = timeStamp + (load ? 30000 : 60000); //缓存60秒  
		uni.setStorageSync('ad_expiration', expiration);
	},

	// 跳转页面
	goToUrl: (url, type = 'navigateTo') => {
		// type: navigateTo 跳转到应用内的某个页面(默认)
		// type：redirectTo 关闭当前页面，跳转到应用内的某个页面。
		// type：reLaunch 关闭所有页面，打开到应用内的某个页面。
		// type：switchTab 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。。
		// type：preloadPage 预加载页面，是一种性能优化技术。被预载的页面，在打开时速度更快。（支持h5和app）
		if (type === 'redirectTo') {
			uni.redirectTo({
				url: url
			})
		} else if (type === 'reLaunch') {
			uni.reLaunch({
				url: url
			})
		} else if (type === 'switchTab') {
			uni.switchTab({
				url: url
			})
		} else if (type === 'preloadPage') {
			uni.preloadPage({
				url: url
			})
		} else {
			uni.navigateTo({
				url: url,
				routeParams: {
					auto: true
				}
			})
		}

	},

	// 设置token
	setToken(token) {
		// 设置token缓存
		uni.setStorageSync('token', token);
		// 当前时间
		// let timeStamp = Date.parse(new Date());
		// // 设置过期期限
		// let expiration = timeStamp + 86400000; //缓存1天  
		// uni.setStorageSync('data_expiration', expiration);
	},

	// 判断token是否过期，如果过期了，清除token与时间
	_isExpiration() {
		// 当前时间
		let timeStamp = Date.parse(new Date());
		//获取过期时间
		let data_expiration = uni.getStorageSync('data_expiration');

		// 如果缓存中没有data_expiration，说明也没有token，还未登录
		if (data_expiration) {
			// 如果超时了，清除缓存，重新登录
			if (timeStamp > data_expiration) {
				uni.removeStorageSync('token');
				uni.removeStorageSync('userInfo');
				uni.removeStorageSync('data_expiration');
				// uni.clearStorageSync();
				return true;
			} else {
				return false;
			}

		}
		return true;
	},
	//保存图片 url:网络地址
	async saveImage(url) {
		return new Promise((resolve, reject) => {
			if (url.indexOf('ttfile://user') != -1) {
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success: () => {
						uni.showToast({
							icon: 'success',
							title: "保存成功",
						});
						resolve("保存成功")
					},
					fail: () => {
						uni.showToast({
							title: "保存失败",
							icon: 'fail'
						});
						reject("保存失败");
					},
				});
			} else {
				// 先下载图片
				uni.downloadFile({
					url: url,
					success: (res) => {
						console.log(res)
						// 获取到图片本地地址后再保存图片到相册（因为此方法不支持远程地址）
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									icon: 'success',
									title: "保存成功",
								});
								resolve("保存成功")
							},
							fail: () => {
								uni.showToast({
									title: "保存失败",
									icon: 'fail'
								});
								reject("保存失败");
							},
						});
					},
					fail: () => {
						reject("保存失败");
					}
				});
			}

		})

	},


	//保存图片 url:网络地址
	async saveVideo(url) {
		if (url.indexOf('ttfile://user') != -1) {
			await uni.saveVideoToPhotosAlbum({
				filePath: url,
				success: () => {
					uni.showToast({
						icon: 'success',
						title: "保存成功",
					});
				},
				fail: () => {
					uni.showToast({
						title: "保存失败",
						icon: 'fail'
					});
				},
			});
		} else {
			// 先下载图片
			await uni.downloadFile({
				url: url,
				success: (res) => {
					console.log(res)
					// 获取到图片本地地址后再保存图片到相册（因为此方法不支持远程地址）
					uni.saveVideoToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							uni.showToast({
								icon: 'success',
								title: "保存成功",
							});
						},
						fail: () => {
							uni.showToast({
								title: "保存失败",
								icon: 'fail'
							});
						},
					});
				},
			});
		}

	},
	async urlTobase64(url) {
		return new Promise((resolve) => {
			// #ifdef MP-WEIXIN
			uni.getFileSystemManager().readFile({
				filePath: url, //选择图片返回的相对路径
				encoding: 'base64', //编码格式
				success: res => { //成功的回调
					let base64 = 'data:image/jpeg;base64,' + res.data; //不加上这串字符,在页面无法显示的哦
					resolve(base64 || '');
				},
				fail: err => {
					console.log("图片转换失败");
					resolve(err);
				}
			})
			// #endif
			// #ifndef MP-WEIXIN
			uni.request({
				url: url,
				method: 'GET',
				responseType: 'arraybuffer',
				success: res => {
					let base64 = uni.arrayBufferToBase64(res
						.data); //jearraybutffer转成base64
					base64 = 'data:image/jpeg;base64,' + base64; //不加上这串字符,在页面无法显示的哦
					resolve(base64 || '');
				},
				fail: (e) => {
					console.log("图片转换失败");
					resolve('');
				}
			})
			//#endif
		})
	},
	// base64转成本地图片路径
	base64ToImage(base64, type) {
		var fs = uni.getFileSystemManager();
		let path = '',
			suffix = '.jpeg',
			imageData = '';
		// 获取本地环境
		// #ifdef MP-WEIXIN
		path = wx.env.USER_DATA_PATH;
		// #endif
		// #ifdef MP-TOUTIAO
		path = tt.getEnvInfoSync().common.USER_DATA_PATH;
		// #endif
		if (type == 'video') {
			suffix = '.mp4';
		}
		var imgPath = path + '/photoRepair' + Date.parse(new Date()) + suffix;
		if (type == 'video') {
			imageData = base64.replace(/^data:video\/mp4;base64,/, ""); //data:video/mp4;base64,
		} else {
			imageData = base64.replace(/^data:image\/\w+;base64,/, ""); //data:image/jpeg;base64,
		}
		// uni.showLoading({
		// 	title:'图片加载中...'
		// })
		let arrayBuffer = uni.base64ToArrayBuffer(imageData);
		fs.writeFileSync(imgPath, arrayBuffer, 'utf8');
		// fs.writeFileSync(imgPath, imageData, 'base64');


		// uni.showToast({
		// 	title:'加载成功!',
		// 	icon:"success"
		// })
		return imgPath;
	},
	// 压缩base64
	async compress(base64String, maxWidth, quality) {
		console.log(base64String, 'base64String');
		const mimeType = base64String.match(/:(.*?);/)[1];
		const image = new Image();

		const promise = new Promise(resolve => {
			image.onload = resolve;
			image.src = base64String;
		});

		await promise;

		let width = image.width;
		let height = image.height;

		if (Math.max(width, height) > maxWidth) {
			if (width > height) {
				height *= maxWidth / width;
				width = maxWidth;
			} else {
				width *= maxWidth / height;
				height = maxWidth;
			}
		}

		const canvas = document.createElement('canvas');
		canvas.width = width;
		canvas.height = height;

		const context = canvas.getContext('2d');
		context.clearRect(0, 0, width, height);
		context.drawImage(image, 0, 0, width, height);

		return canvas.toDataURL(mimeType, quality);
	},

	// 删除本地图片
	clearFsUlinkSync(url) {
		const fs = uni.getFileSystemManager();
		try {
			fs.unlinkSync(url);
			console.log("删除成功!");
		} catch (e) {
			// console.log("删除失败!");
		}
	},
	compressVideoFn(url, quality) {
		uni.downloadFile({
			url: url, //仅为示例，并非真实的资源
			success: (res) => {
				if (res.statusCode === 200) {
					console.log(res, '下载成功');
					return res.tempFilePath;
				} else {
					return url;
				}
			}
		});
		// uni.compressVideo({
		// 	src,
		// 	quality,
		// 	success(res) {
		// 		console.log(res.tempFilePath);
		// 		return res.tempFilePath;
		// 	}
		// })
	},

	downloadFileFn(url) {
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url, //仅为示例，并非真实的资源
				success: (res) => {
					if (res.statusCode === 200) {
						resolve(res.tempFilePath);
					} else {
						resolve('');
					}
				},
				fail: () => {
					resolve('');
				}
			});

		})

	},
	developingToast() {
		uni.showToast({
			title: '正在开发 敬请期待!',
			icon: "none",
		})
	},

	// 获取用户信息
	getUserInfo() {
		return new Promise((resolve, reject) => {
			userInfo({
				data: {
					...ajaxParams,
					token: uni.getStorageSync("token")
				},
			}).then(res => {
				if (res.code == 200) {
					uni.setStorageSync('userInfo', res.result);
					// 数据不存在，清除所有缓存
					if (res.result == null) {
						uni.clearStorageSync();
					}
				}
				resolve(res);
			}).catch(err => {
				console.log(err, 'err');
				resolve(err)
			})
		})
	},

	// 判断是否为今日头条安卓版
	isToutiaoAndroid() {
		// #ifdef MP-TOUTIAO
		try {
			const res = uni.getSystemInfoSync();
			return this.isToutiao() && res.platform == 'android'
			console.log("获取系统信息成功: ", res);
		} catch (error) {
			console.log("获取系统信息失败: ", error);
		}
		// #endif
		// #ifndef MP-TOUTIAO
		return false;
		// #endif
	},

	isToutiao() {
		// #ifdef MP-TOUTIAO
		try {
			const res = uni.getSystemInfoSync();
			return (res.hostName == 'Toutiao' || res.hostName == 'news_article_lite')
			console.log("获取系统信息成功: ", res);
		} catch (error) {
			console.log("获取系统信息失败: ", error);
		}
		// #endif
		// #ifndef MP-TOUTIAO
		return false;
		// #endif
	},


	// requestPayment 支付模块二次封装
	payMent(orderInfo) {

		let newObj = {
			timeStamp: orderInfo.timeStamp,
			nonceStr: orderInfo.nonceStr,
			package: orderInfo.packageValue,
			signType: orderInfo.signType,
			paySign: orderInfo.paySign,
		}
		return new Promise((resolve, reject) => {
			uni.requestPayment({
				...newObj,
				success(res) {
					resolve(res)
				},
				fail(err) {
					console.log(err);
					resolve(err)
				}
			})
		})
	},

	getMenuButton() {
		// 获取导航栏的高度（手机状态栏高度 + 胶囊高度 + 胶囊的上下间距）
		const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
		return {
			top: menuButtonInfo.top * 2,
			height: menuButtonInfo.height * 2
		}
	},

	showToast(title, type = 'success', duration = 3000) {
		uni.showToast({
			title,
			type,
			duration,
		})
	},
	// 设置必点菜品
	setMustSelectedFoods(data,mustSelectedFoods){
		console.log(mustSelectedFoods,'mustSelectedFoods');
		if(mustSelectedFoods && mustSelectedFoods.length){
			let mustSelectedFoodsData = {storeId:data.storeId,storeName:data.storeName,mustSelectedFoods}
			let mustSelectedFoodsStorage = uni.getStorageSync('mustSelectedFoodsStorage');
			let newMustSelectedFoods;
			if(mustSelectedFoodsStorage){
				newMustSelectedFoods = JSON.parse(mustSelectedFoodsStorage);
				// 如果缓存里没有当前店铺的必点信息，则添加，否则替换
				let mustSelectedFoodsIndex = newMustSelectedFoods.findIndex(item=>item.storeId == mustSelectedFoodsData.storeId)
				console.log(mustSelectedFoodsIndex ,'index');
				if(mustSelectedFoodsIndex == -1){
					newMustSelectedFoods.push(mustSelectedFoodsData)
				}else{
					newMustSelectedFoods[mustSelectedFoodsIndex] = mustSelectedFoodsData;
				}
			}else{
				newMustSelectedFoods = [mustSelectedFoodsData];
			}
			uni.setStorageSync('mustSelectedFoodsStorage',JSON.stringify(newMustSelectedFoods));
		}
	},
	// 查询必选菜品
	isMustPurchase(shopCarList){
		console.log(shopCarList,'shopCarList');
		// 获取菜品列表
		// 获取店铺的的必选菜品
		let mustSelectedFoodsStorage =  uni.getStorageSync("mustSelectedFoodsStorage");
		if(mustSelectedFoodsStorage){
			let MustSelectedFoodsStorage = JSON.parse(mustSelectedFoodsStorage);
			// 数组，存储必选菜品是否已经选择
			let mustSelectedFoodsArray = [];
			
			MustSelectedFoodsStorage.forEach(item=>{
				// 判断选中的菜品是否有必选的菜品 
				let isStore = shopCarList.some(items=>items.storeId == item.storeId)
				// 循环必选菜品列表
				isStore && item.mustSelectedFoods.forEach(foodIds=>{
					mustSelectedFoodsArray.push({
						storeId:item.storeId,
						storeName:item.storeName,
						type:shopCarList.some(items=> items.storeId == item.storeId && foodIds == items.foodId)  //如果已经选中为true 否则为false
					})
				})
			})
			let item = mustSelectedFoodsArray.find(item=>item.type == false)
			if(item){
				return item;
			}
		}
		return null;
	},
	base64src(base64data) {
		const fsm = uni.getFileSystemManager();
		const FILE_BASE_NAME = 'tmp_base64src';
		return new Promise((resolve, reject) => {
			const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
			if (!format) {
				reject(new Error('ERROR_BASE64SRC_PARSE'));
			}
			var num = Math.round(Math.random() * 10000);
			const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}${num}.${format}`;
			const buffer = uni.base64ToArrayBuffer(bodyData);
			fsm.writeFile({
				filePath,
				data: buffer,
				encoding: 'binary',
				success() {
					resolve(filePath);
				},
				fail() {
					reject(new Error('ERROR_BASE64SRC_WRITE'));
				},
			});
		});
	},
	//获取userId
	getUserId() {
		let token = uni.getStorageSync('token').split('.');
		if(token){
			let userinfo = token[1].replace(/-/g, '+').replace(/_/g, '/')
			// 解码base
			let info = new Buffer(userinfo, 'base64').toString('utf8')
			let userId = JSON.parse(info).username.split('token_')[1]
			return userId;
		}else{
			return '';
		}
		
	},
	

	
	//获取token 过期时间
	getTokenExp() {
		let token = uni.getStorageSync('token');
		console.log(token,'token');
		if(token){
			let userinfo = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
			// 解码base
			let info = new Buffer(userinfo, 'base64').toString('utf8')
			return JSON.parse(info).exp
		}else {
			return 0;
		}
		
	},

	// 设置邀请人id
	async sendSharedUserIdFn() {
		let sharedUserId = uni.getStorageSync('sharedUserId')
		if (sharedUserId) {
			let res = await sendSharedUserId({
				method: "PUT",
				data: {
					sharedUserId: uni.getStorageSync('sharedUserId')
				},
			})
			uni.showToast({
				title: res.message,
				icon: 'none'
			})
			uni.removeStorageSync('sharedUserId')
		}
	},
	
	// 设置点餐页面缓存
	setStorePage(datas){
		let storePage = uni.getStorageSync('storePage');
		let newStorePage = {};
		for(var i = 0;i <datas.length; i++){
			newStorePage[datas[i].name] = datas[i].data;
		}
		if(storePage){
			storePage = JSON.parse(storePage);
			if(datas[0]?.name == "currAddress" && storePage['currAddress'] &&  datas[0].siteId != storePage['currAddress'].siteId){
				storePage = {...newStorePage}
				console.log(1,storePage);
			}else{
				console.log(2,storePage,newStorePage);
				storePage = {...storePage,...newStorePage}
			}
		}else {
			storePage = newStorePage;
		}
		uni.setStorageSync('storePage', JSON.stringify(storePage))
	},
	// 获取点餐页面缓存
	getStorePage(){
		let storePage = uni.getStorageSync('storePage');
		let data = {};
		if(storePage){
			data = JSON.parse(storePage);
		}
		return data;
	},



}